import {Component, ViewChild} from '@angular/core';
import {StatusBar} from '@ionic-native/status-bar';
import {SplashScreen} from '@ionic-native/splash-screen';

import {IonicApp, Keyboard, Nav, Platform} from "ionic-angular";
import {AppPopup} from "../util/popup";
import {services} from "../providers/service";
import {TabsPage} from "../pages/tabs/tabs";
import {UserService} from "../providers/user-service";
import {UserLogin} from "../modules/app-user/user-login/user-login";
import {Device} from "@ionic-native/device";

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild('myNav') nav: Nav;
  backButtonPressed: boolean = false;

  rootPage: any ;

  constructor(private platform: Platform,
              private statusBar: StatusBar,
              private splashScreen: SplashScreen,
              private keyboard: Keyboard,
              private userServ: UserService,
              private device: Device,
              private ionicApp: IonicApp,
              private service: services,
              private popup: AppPopup
  ) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();
      this.registerBackButtonAction();//注册返回按键事件
      this.autoLogin();
    });
  }

  autoLogin() {
    if(localStorage.getItem("user")){
      let param = localStorage.getItem("user");
      this.userServ.getLocalId(JSON.parse(param))
          .then(res => {
            if(res.infoData == this.device.uuid) {
              // this.rootPage = TabsPage;
              this.userServ.login(JSON.parse(param))
                  .then(rs => {
                    this.rootPage = TabsPage;
                  })
                  .catch(err => {
                    this.rootPage = TabsPage;
                  })
            } else {
              localStorage.removeItem("user");
              this.rootPage = UserLogin;
            }
          })
          .catch(err => {
            this.rootPage = UserLogin;
          })
      // this.userServ.login(JSON.parse(param))
      //     .then(res => {
      //
      //       return this.userServ.getLocalId({loginName: res.infoData.loginName});
      //         // this.service.infoData.id = res.infoData.id;
      //         // this.service.infoData.loginName = res.infoData.loginName;
      //         // this.rootPage = TabsPage;
      //     })
      //     .then(res => {
      //       console.info("获取设备唯一表示",res);
      //       if(res.infoData == this.device.uuid) {
      //         this.rootPage = TabsPage;
      //       }else {
      //         localStorage.removeItem("user");
      //         this.rootPage = UserLogin;
      //       }
      //     })
      //     .catch(err => {
      //       this.rootPage = UserLogin;
      //       console.error(err);
      //     })
    }else {
      this.rootPage = UserLogin;
    }
  }

  registerBackButtonAction() {
    this.platform.registerBackButtonAction(() => {
      console.info("=============",this.service.isReturn);
      if(this.service.isReturn){
        this.service.isReturn = false;
        return;
      }

      if (this.keyboard.isOpen()) {//如果键盘开启则隐藏键盘
        this.keyboard.close();
        return;
      }
      //如果想点击返回按钮隐藏toast或loading或Overlay就把下面加上
      // this.ionicApp._toastPortal.getActive() ||this.ionicApp._loadingPortal.getActive()|| this.ionicApp._overlayPortal.getActive()
      let activePortal = this.ionicApp._modalPortal.getActive();
      if (activePortal) {
        activePortal.dismiss();
        return;
      }
      let activeVC = this.nav.getActive();
      console.log("-----------------",activeVC);
      if(activeVC.name == "UserLogin"){
        this.platform.exitApp();
      }else if(activeVC.name == "FindPwd"){
        activeVC.instance.navCtrl.pop();
      }else {
        let tabs = activeVC.instance.tabs;
        let activeNav = tabs.getSelected();
        return activeNav.canGoBack() ? activeNav.pop() : this.showExit();
      }

    }, 1);
  }

  //双击退出提示框
  showExit() {
    if (this.backButtonPressed) { //当触发标志为true时，即2秒内双击返回按键则退出APP
      this.platform.exitApp();
    } else {
      this.popup.toast('再按一次退出应用','bottom',2000);
      this.backButtonPressed = true;
      setTimeout(() => { //2秒内没有再次点击返回则将触发标志标记为false
        this.backButtonPressed = false;
      }, 2000)
    }
  }
}
